package love.链表;

/**
 * @author: levi
 * @description: 直接指向，就是同一个，next就是下一个
 * @date: 2022-9-6 13:04
 * @version: 1.0
 */
public class LinkedList<E> extends AbstractList<E>{
    // 头节点
    private Node<E> first;

    // 内部类。Node节点类
    private static class Node<E>{
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;//头结点直接置空，头节点也不要了。
    }

    @Override
    public E get(int index) {
        return getNodeByIndex(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> nodeByIndex = getNodeByIndex(index);
        E oldData = nodeByIndex.element;
        nodeByIndex.element = element;
        return oldData;
    }

    @Override
    public void add(int index, E element) {
        if(index == 0){
            first = new Node<E>(element,first);
        }else {
            Node<E> preNode = getNodeByIndex(index - 1);
            preNode.next = new Node<>(element,preNode.next);
        }
        size ++;
    }

    @Override
    public E remove(int index) {
        E element = first.element;
        if(index == 0){
            first = first.next;
        }else {
            Node<E> preNode = getNodeByIndex(index - 1);
            element = preNode.next.element;
            preNode.next = preNode.next.next;

        }
        size --;
        return element;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (node.element == null) return i;
                node = node.next;
            }
        } else {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (element.equals(node.element)) return i;
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size=").append(size).append(", [");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }

            string.append(node);

            node = node.next;
        }
        string.append("]");
        return string.toString();
    }

    /**
     * @Description 根据下标位置返回链表节点
     * @Param  * @param index
     * @return love.链表.LinkedList.Node<E>
     **/
    private Node<E> getNodeByIndex(int index){
        // 下标校验
        rangeCheck(index);
        // 创建节点，指向first，意思就是和first是一个东西了,指向初始位置
        Node<E> node = first;
        // 遍历查询，传入Index位置，就是遍历Index次
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }
}
